package cmd

import (
	"fmt"
	"github.com/CIPFZ/collector/internal/app"
	"github.com/CIPFZ/collector/internal/core"
	"github.com/CIPFZ/collector/internal/types"
	"github.com/CIPFZ/collector/pkg/exception"

	"github.com/spf13/cobra"
	"go.uber.org/zap"
)

// NewStatusCommand 创建 status 命令
func NewStatusCommand(collector *app.Collector) *cobra.Command {
	var opts types.StatusOptions

	cmd := &cobra.Command{
		Use:   "status",
		Short: "Show current collection status",
		Long: `Display the status of currently running or recent collection tasks.

Examples:
  collector status                     # Show status in human-readable format
  collector status --json             # Show status in JSON format`,
		RunE: func(cmd *cobra.Command, args []string) error {
			if opts.TaskID == "" {
				return exception.NewNotTaskIdError("missing required flag: --task-id")
			}

			logger := collector.Logger()
			logger.Info("Checking collection status",
				zap.Bool("json", opts.JsonOutput),
				zap.String("task-id", opts.TaskID))

			// 状态查询
			statusManager := core.NewTaskStatusManager(collector.Config().Output.Dir, false)
			task, err := statusManager.GetTaskStatus(opts.TaskID)
			if err != nil {
				logger.Error("Failed to get task status",
					zap.String("task-id", opts.TaskID),
					zap.Error(err))
				return err
			}
			// 输出结果
			fmt.Println(task.Print(opts.JsonOutput))
			return nil
		},
	}

	cmd.Flags().StringVar(&opts.TaskID, "task-id", "",
		"specific core ID to cancel")
	cmd.Flags().BoolVar(&opts.JsonOutput, "json", false,
		"output status in JSON format")

	return cmd
}
